package com.example.springbootvuedemo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootvuedemo.controller.utils.R;
import com.example.springbootvuedemo.domain.Book;
import com.example.springbootvuedemo.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookServiceImpl bookService;
    @GetMapping
    public R getAll(){
        return new R(true,bookService.getAll());
    }
    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        //其他的也要改成这样，为了表现层抛出异常格式的统一
        boolean flag=bookService.save(book);
        return new R(flag,flag?"添加成功":"添加失败");
    }
    @PutMapping
    public R update(@RequestBody Book book){
        return new R(bookService.update(book));
    }
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.delete(id));
    }
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }
    @GetMapping("{current}/{size}")
    public R getByPage(@PathVariable Integer current,@PathVariable Integer size){
        IPage<Book> page = bookService.getByPage(current, size);
        //防止一页里只有一行数据，删除后，显示无数据
        Integer temp= (int)page.getPages();
        if(current>temp){
            page=bookService.getByPage(temp, size);
        }
        return new R(true,page);
    }
    @GetMapping("{current}/{size}/{s}")
    public R getByPageSelect(@PathVariable Integer current,@PathVariable Integer size,@PathVariable String s, Book book){
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxx");
        IPage<Book> page= bookService.getByPageSelect(current,size,book);
        Integer temp= (int)page.getPages();
        if(current>temp){
            page=bookService.getByPageSelect(temp, size, book);
        }
        return new R(true,page);
    }
}
